package unimelb.filesync.server.protocol;

import java.net.ServerSocket;
import java.net.Socket;

import unimelb.filesync.common.misc.ProtocolContext;
import unimelb.filesync.common.network.NetworkConnection;
import unimelb.filesync.common.protocol.IFileSyncPhase;

public class ListenForConnectionPhase implements IFileSyncPhase {

    private final ProtocolContext context;

    public ListenForConnectionPhase(ProtocolContext context) {
        super();
        this.context = context;
    }

    @Override
    public void execute() {
        try {
            final Integer port = context.getObject(ProtocolContext.PORT);
            final ServerSocket serverSocket = new ServerSocket(port);
            context.addObject(ProtocolContext.SERVER_SOCKET, serverSocket);

            final Socket hotLineSocket = serverSocket.accept();
            context.addObject(ProtocolContext.HOT_LINE_CONNECTION, new NetworkConnection(hotLineSocket));
        } catch (Exception exeption) {
            throw new RuntimeException(exeption);
        }
    }
}
